<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="环节名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入环节名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会场" prop="placeId">
        <el-select v-model="queryParams.placeId" filterable remote reserve-keyword placeholder="请选择会场" :remote-method="queryRemoteMethod" :loading="queryPlaceIdLoading" style="width: 240px">
          <el-option
            v-for="item in queryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" />
      <el-table-column label="环节名称" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="所属会场" prop="placeName" :show-overflow-tooltip="true" />
      <el-table-column label="主席" prop="chairmans">
        <template slot-scope="scope">
          <span>{{ scope.row.chairmans | getFullName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主持" prop="hosts">
        <template slot-scope="scope">
          <span>{{ scope.row.hosts | getFullName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日程数量" prop="programmeCount" />
      <el-table-column label="演讲日期" align="center" prop="startDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="90px" style="height: 500px; overflow: auto">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础信息" name="first">
            <el-form-item label="环节名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入环节名称" clearable />
            </el-form-item>
            <el-form-item label="所属会场" prop="placeId">
              <el-select v-model="form.placeId" filterable remote reserve-keyword placeholder="请选择会场名称" :remote-method="remoteMethod" :loading="placeIdLoading" style="width: 370px">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" value-format="timestamp" placeholder="请选择日期" clearable style="width: 370px" />
            </el-form-item>
            <el-form-item label="主席" prop="chairmanList">
              <el-select v-model="form.chairmanList" multiple filterable remote reserve-keyword placeholder="请选择主席" :remote-method="remoteMethod2" :loading="placeIdLoading2" @change="handleChairmanChange" style="width: 370px">
                <el-option
                  v-for="item in options2"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="主持" prop="hostList">
              <el-select v-model="form.hostList" multiple filterable remote reserve-keyword placeholder="请选择主持" :remote-method="remoteMethod3" :loading="placeIdLoading3" @change="handleHostChange" style="width: 370px">
                <el-option
                  v-for="item in options3"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="嘉宾头衔" name="second">
            <el-collapse v-model="activeNames" @change="handleChange">
              <el-collapse-item title="主席头衔" name="1">
                <template v-for="item in form.chairmans">
                  <el-form-item :label="item.speakerName">
                    <el-input v-model="item.speakerTitle" placeholder="请输入主席头衔" @change="handleChairmanTitleChange(item)" clearable />
                  </el-form-item>
                </template>
              </el-collapse-item>
              <el-collapse-item title="主持头衔" name="2">
                <template v-for="item in form.hosts">
                  <el-form-item :label="item.speakerName">
                    <el-input v-model="item.speakerTitle" placeholder="请输入主持头衔" @change="handleHostTitleChange(item)" clearable />
                  </el-form-item>
                </template>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {listPlace} from "@/api/meetingManagement/place";
import {addMatter, listMatter, updateMatter, delMatter} from "@/api/meetingManagement/matter";
import {listSpeaker} from "@/api/meetingManagement/speaker";
export default {
  name: "MeetingSchedule",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
      },
      // 表单参数
      form: {
        title: null,
        chairmans: [],
        chairmanList: [],
        placeId: null,
        startDate: null,
        hosts: [],
        hostList: []
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "环节名称不能为空", trigger: "blur" }
        ],
        placeId: [
          { required: true, message: "请选择所属会场", trigger: "change" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      dialogVisible: false,
      placeIdLoading: false,
      options: [],
      queryOptions: [],
      queryPlaceIdLoading: false,
      placeIdLoading2: false,
      options2: [],
      placeIdLoading3: false,
      options3: [],
      activeName: 'first',
      activeNames: ['1']
    }
  },
  mounted() {
    this.queryParams.meetId = this.$route.params && this.$route.params.id
    this.getList()
    this.queryRemoteMethod()
  },
  filters: {
    getFullName: function(value) {
      if (value) {
        return value.map(item => item.fullName).join(',')
      } else {
        return ''
      }
    }
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listMatter(this.addDateRange(this.queryParams)).then(response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      })
      this.form = {
        title: null,
        chairmans: [],
        chairmanList: [],
        placeId: null,
        startDate: null,
        hosts: [],
        hostList: []
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.remoteMethod()
      this.remoteMethod2()
      this.remoteMethod3()
      this.title = "添加会议环节"
      this.dialogVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.activeName = "first"
      this.remoteMethod()
      this.remoteMethod2()
      this.remoteMethod3()
      this.form = {...row}
      this.form.chairmanList = this.form.chairmans.map(item => item.speakerId)
      this.form.hostList = this.form.hosts.map(item => item.speakerId)
      setTimeout(() => {
        this.handleTitle()
      }, 300)
      this.title = "修改会议环节"
      this.dialogVisible = true
    },
    handleTitle() {
      if (this.options2?.length > 0) {
        // 创建新数组，触发响应式更新
        this.form.chairmans = this.form.chairmans.map(item => {
          const speaker = this.options2.find(sel => item.speakerId === sel.id)
          if (speaker) {
            return {
              ...item,
              speakerName: speaker.name,
              speakerTitle: item.fullName.replace(speaker.name, '')
            }
          }
          return item
        })

        this.form.hosts = this.form.hosts.map(item => {
          const speaker = this.options2.find(sel => item.speakerId === sel.id)
          if (speaker) {
            return {
              ...item,
              speakerName: speaker.name,
              speakerTitle: item.fullName.replace(speaker.name, '')
            }
          }
          return item
        })
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.meetId = this.queryParams.meetId
          if (this.form.id != undefined) {
            updateMatter(this.form).then(response => {
              this.$modal.msgSuccess(response.msg || "修改成功")
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addMatter(this.form).then(response => {
              this.$modal.msgSuccess(response.msg || "新增成功")
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id
      this.$modal.confirm('是否确认删除会议环节编号为"' + roleIds + '"的数据项？').then(function() {
        return delMatter(roleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    remoteMethod(query) {
      if (query !== '') {
        this.placeIdLoading = true;
        listPlace({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.options = response.rows
          this.placeIdLoading = false
        })
      } else {
        this.options = [];
      }
    },
    remoteMethod2(query) {
      if (query !== '') {
        this.placeIdLoading2 = true;
        listSpeaker({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.options2 = response.rows
          this.options2.forEach((item) => {
            item.name = item.lastName + item.firstName
          })
          this.placeIdLoading2 = false
        })
      } else {
        this.options2 = [];
      }
    },
    remoteMethod3(query) {
      if (query !== '') {
        this.placeIdLoading3 = true;
        listSpeaker({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.options3 = response.rows
          this.options3.forEach((item) => {
            item.name = item.lastName + item.firstName
          })
          this.placeIdLoading3 = false
        })
      } else {
        this.options3 = [];
      }
    },
    queryRemoteMethod(query) {
      if (query !== '') {
        this.queryPlaceIdLoading = true;
        listPlace({
          name: query,
          pageNum: 1,
          pageSize: 200,
          meetId: this.queryParams.meetId
        }).then(response => {
          this.queryOptions = response.rows
          this.queryPlaceIdLoading = false
        })
      } else {
        this.queryOptions = [];
      }
    },
    handleClick(tab) {
      this.activeName = tab.name
    },
    handleChange(val) {
      console.log(val);
    },
    handleChairmanChange(val) {
      let list = []
      if (val?.length > 0) {
        val.forEach(item => {
          this.options2.forEach(item2 => {
            if (item2.id === item) {
              let json = {
                speakerId: item2.id,
                speakerName: item2.name,
                meetId: this.queryParams.meetId
              }
              list.push(json)
            }
          })
        })
      } else {
        list = []
      }
      this.form.chairmans = list
    },
    handleHostChange(val) {
      let list = []
      if (val?.length > 0) {
        val.forEach(item => {
          this.options3.forEach(item3 => {
            if (item3.id === item) {
              let json = {
                speakerId: item3.id,
                speakerName: item3.name,
                meetId: this.queryParams.meetId
              }
              list.push(json)
            }
          })
        })
      } else {
        list = []
      }
      this.form.hosts = list
    },
    handleChairmanTitleChange(item) {
      item.fullName = item.speakerName + item.speakerTitle
    },
    handleHostTitleChange(item) {
      item.fullName = item.speakerName + item.speakerTitle
    }
  }
}
</script>
<style scoped lang="scss">

</style>
